package com.itheima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.VO.AdUserVO;
import com.heima.model.common.admin.pojos.AdUser;
import com.heima.model.common.dtos.AdUserDTO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import com.itheima.admin.mapper.AdUserMapper;
import com.itheima.admin.service.AdUserService;
import com.itheima.common.exception.CustException;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    @Override
    public ResponseResult login(AdUserDTO dto) {
        //1 校验参数
        if(dto == null ){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 根据用户名查询用户信息
        AdUser user = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        if (user==null ){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户名或者密码错误");
        }
        if (user.getStatus().intValue()!=9){
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }
        //3 获取数据库密码和盐值
        String password = user.getPassword();
        String salt = user.getSalt();
        //用户输入密码验证
        String md5DigestAsHex = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
        if (!md5DigestAsHex.equals(password)){
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"用户名或者密码错误");
        }
        //4 修改登录时间
        user.setLoginTime(new Date());
        updateById(user);
        //5  颁发token
        String token = AppJwtUtil.getToken(user.getId().longValue());
        //6 用户信息返回
        AdUserVO adUserVO = new AdUserVO();
        try {
            BeanUtils.copyProperties(user,adUserVO);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 7 返回结果
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("user",adUserVO);
        return ResponseResult.okResult(map);
    }
}
